﻿using System;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using mozhi.smarterp.BasicData.Employees.Repositories;
using Volo.Abp.Guids;
using Mozhi.Abp.Domain.AuthorCenter;

namespace mozhi.smarterp.BasicData.Employees.Services
{
    public class EmployeeManager : DomainService
    {
        private IEmployeeRepository _repository;
        private IDepartmentRepository _departmentRepository;
        private IGuidGenerator _guidGenerator;

        public EmployeeManager(IEmployeeRepository repository , IDepartmentRepository departmentRepository , IGuidGenerator guidGenerator)
        {
            _repository = repository;
            _departmentRepository = departmentRepository;
            _guidGenerator = guidGenerator;
        }

        public async Task<Employee> GetAysnc(Guid? id, string code, string name, Guid? departmentId, string phone, string email, bool activated)
        {
            var matchCount = await _repository.GetCountAsync(code, id);

            if (matchCount > 0)
                throw new UserFriendlyException("编码或者名称已经存在", "100000");

            await ValidateDepartmentAsync(departmentId);

            Employee employee;

            if (id.HasValue)
            {
                employee = await _repository.GetAsync(id.Value);
                employee.Change(code, name, departmentId, phone, email, activated);
            }
            else
                employee = new Employee(_guidGenerator.Create(), code, name, departmentId, phone, email, activated);

            return employee;
        }


        #region
        private async Task ValidateDepartmentAsync(Guid? departmentId)
        {
            if (!departmentId.HasValue)
                return;

            var department = await _departmentRepository.GetAsync(departmentId.Value);

            if (department == null)
                throw new UserFriendlyException("部门不存在", "100000");

            if (!department.Activated)
                throw new UserFriendlyException("部门已禁用", "100000");
        }
        #endregion
    }
}
